<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { getPatientDetail} from '@/api/user'
import { getConsultOrderPre,createConsultOrder } from '@/api/consult';
import type { ConsultOrderPreData } from '@/types/consult'
import { useConsultStore } from '@/stores';
import type {Patient} from '@/types/user'
import {  Dialog, showConfirmDialog, showToast } from 'vant';
import { onBeforeRouteLeave, useRouter } from 'vue-router';
const router = useRouter()
const store = useConsultStore()
// 1.获取支付信息
const payInfo = ref<ConsultOrderPreData>()
const getPayInfo = async () => {
    const res = await getConsultOrderPre({
        type: store.consult.type, // 问诊类型:极速问诊
        illnessType: store.consult.illnessType // 问诊级别：三甲或普通
    })
    payInfo.value = res.data
    console.log(payInfo.value);
}
// 获取患者信息
const patientInfo = ref<Patient>()
const getPatient = async () => {
    const patientId = store.consult.patientId
    if(patientId){
        const res = await getPatientDetail(patientId)
        patientInfo.value = res.data
    }
}
// 保存支付订单ID
const orderId = ref<string>('')
// 支付协议
const agree = ref(false)
// 点击立即支付打开支付弹层
const show = ref(false)
// 支付方式
const paymentMethod = ref<'0'|'1'>()
// 支付函数
const openFn = async () => {
    if(!agree.value){
      showToast({
        message: '请先同意支付协议',
        className: 'particulars-detail-popup'
      })
        return false
    }
    show.value = true
    // 创建订单
    try{
      const {data} = await createConsultOrder(store.consult)
      orderId.value = data.id
      // 订单创建成功则需要清空pinia中的数据
      store.clear()
    }catch(err){
      router.push('/layout')
      console.log(err)
      // 访问了这个支付页面但是缺少问诊数据跳转到首页

    }
    if(paymentMethod.value === '0'){
        // 微信支付
    }else{
        // 支付宝支付
    }
}
// 支付窗口打开后订单创建成功页面禁止跳转回退
onBeforeRouteLeave(()=>{
    if(orderId.value){
        return false
    }
    onClose()
})

// 异步关闭
// 通过 beforeClose 属性可以传入一个回调函数，在弹窗关闭前进行特定操作。

// 控制是否关闭支付窗口
// const onClose = async () => {
//    await  Dialog.confirm({
//     title: '关闭支付',
//     message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
//     cancelButtonText: '仍要关闭',
//     confirmButtonText: '继续支付'
//   })
//     .then(() => {
//       console.log(1);
//       return true
//     })
//     .catch(() => {
//       console.log(2);
//       orderId.value = ''
//       router.push('/layout')
//       return false
//     })
// }
// 定义支付回调地址
const payCallback = '/room'
const onClose =  async () => {
  const res = await showConfirmDialog({
        title: '关闭支付',
        message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
        // closeOnPopstate: false,
        cancelButtonText: '仍要关闭',
        confirmButtonText: '继续支付'
      }).then((res)=> {
        console.log(1);
        console.log(res);
        show.value = false;
        // return false
        return true
      }).catch((err) => {
        console.log(2);
        orderId.value = ''
        console.log(err);
        show.value = false
        router.push('/user/consult')
        return false
      })
  //  try{
  //     await showConfirmDialog({
  //       title: '关闭支付',
  //       message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
  //       // closeOnPopstate: false
  //       cancelButtonText: '仍要关闭',
  //       confirmButtonText: '继续支付'
  //     })
  //     return false
  //  }catch(error) {
  //     console.log(error)
  //     orderId.value = ''
  //     router.push('/user/consult')
  //     return false
  //  }
}
const price = computed(()=>{
    return (payInfo.value?.actualPayment ?? 0) * 100;
})



onMounted(()=>{
 
    getPayInfo()
    getPatient()
})
</script>

<template>
  <div class="consult-pay-page">
    <cp-nav-bar title="支付" />
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo?.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="payInfo?.couponDeduction" />
      <van-cell title="积分抵扣" :value="payInfo?.pointDeduction" />
      <van-cell title="实付款" :value="payInfo?.actualPayment" class="pay-price" />
    </van-cell-group>
    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell title="患者信息" :value="`${patientInfo?.name}|${patientInfo?.gender==0?'女':'男'}|${patientInfo?.age}`"></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree">我已同意 <span class="text">支付协议</span></van-checkbox>
    </div>
    <van-submit-bar button-type="primary" :price="price" button-text="立即支付" text-align="left" @click="openFn" />
  </div>
<cp-pay-sheet :actualPayment="payInfo!?.actualPayment" :orderId="orderId" :show="show" :onClose="onClose" :payCallback="payCallback"></cp-pay-sheet>
</template>

<style lang="scss" scoped>
// .consult-pay-page {
  
// }
.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}
.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}
.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}
::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}
</style>

